/** @jsxRuntime classic */
/** @jsx jsx */ 

/**
 * @description 邮箱提交
 * @author fyj
 */
import React from 'react';
import { Formik, Form, useField } from 'formik';
import * as Yup from 'yup';
import { jsx, css } from '@emotion/react';
import styled from '@emotion/styled';

const myLabelCss = css({
  display: 'block',
  fontWeight: 'bold',
  fontSize: '14px'
});

const myInputCss = css`
  display: block;
  border-radius: 2px;
  margin: 3px 0px 5px;
`;

const Button = styled.button({
  padding: '2px 5px 3px',
  display: 'block',
  color: 'black',
}, props => ({
  color: props.color
}));

const ButtonCopy = styled.button(props => ({
  padding: '2px 5px 3px',
  display: 'block',
  color: props.color || 'black',
}));

const ErrorMsg = styled.div`
  color: ${props => props.color || 'red'};
  font-size: 12px;
`

function MyTextInput({label, ...props}) {
  const [field, meta] = useField(props);
  return (
    <>
      <label css={myLabelCss} htmlFor={props.id || props.name}>{label}</label>
      <input css={myInputCss} {...field} {...props} />
      {
        meta.touched && meta.error 
          ? <ErrorMsg>{meta.error}</ErrorMsg>
          : null
      }
    </>
  )
}

function MyCheckbox({label, ...props}) {
  const [field, meta] = useField(props);
  return (
    <>
      <input {...field} {...props} type="checkbox" />
      <label htmlFor={props.id || props.name}>{label}</label>
      {
        meta.touched && meta.error 
          ? <div>{meta.error}</div>
          : null
      }
    </>
  )
}

function EmailDemo() {
  function handleSubmit(values) {
    console.log(values);
  }

  return (
    <>
      <Formik
        initialValues={{
          firstName: '',
          lastName: '',
          acceptedTerms: false,
        }}
        validationSchema={
          Yup.object({
            firstName: Yup.string().required().max(3, '长度不能超过 15 个字符哟'),
            lastName: Yup.string().required().min(1, '长度大于 1 个字符哟'),
            acceptedTerms: Yup.boolean().required().oneOf([true], 'You must accept the terms and conditions.')
          })
        }
        onSubmit={handleSubmit}
      >
        <Form>
          <MyTextInput 
            name="firstName"
            label="First Name"
            placeholder="Jane"
          />
          <MyTextInput 
            name="lastName"
            label="Last Name"
            placeholder="Done"
          />
          <MyCheckbox 
            label="I accept the terms and conditions"
            name="acceptedTerms"
          />
          <Button type="submit">提交</Button>
        </Form>
      </Formik>
    </>
  )
}

export default EmailDemo;
